package com.woniuxy.rabbit.config;

import com.rabbitmq.client.impl.AMQImpl;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.boot.autoconfigure.amqp.RabbitTemplateConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class MQConfig {
    public static final String USER_EXCHANGE = "user.exchange";
    public static final String USER_QUEUE = "user.queue.message";
    public static final String USER_BINDING = "user.binding";

    private static final String DEAD_EXCHANGE = "order.dead.exchange";
    private static final String DEAD_QUEUE = "order.dead.queue";
    private static final String DEAD_BINDING = "order.dead.binding";

    @Bean
    public Binding getBinding(){
        return BindingBuilder
                .bind(Queue())
                .to(getExchange())
                .with(USER_BINDING);
    }

    @Bean
    public TopicExchange delexchange(){
        return new TopicExchange(DEAD_EXCHANGE);
    }

    @Bean
    public Queue delQueue(){
        return new Queue(DEAD_QUEUE);
    }

    @Bean
    public Binding delBinding(){
        return BindingBuilder
                .bind(delQueue())
                .to(delexchange())
                .with(DEAD_BINDING);
    }

    @Bean
    public TopicExchange getExchange(){
        return new TopicExchange(USER_EXCHANGE);
    }


    /*
    是否持久化

    数据接收是否删除
     */
//    @Bean
//    public Queue getQueue(){
//        return new Queue(USER_QUEUE);
//    }

    @Bean
    public Queue Queue(){
        Map<String,Object> arguments = new HashMap<>();
        // 指定该队列的死信交换机和路由键
        arguments.put("x-dead-letter-exchange",DEAD_EXCHANGE);
        arguments.put("x-dead-letter-routing-key",DEAD_BINDING);
//        arguments.put("x-dead-letter-queue",USER_QUEUE);
        return new Queue(USER_QUEUE,true,false,false,arguments);
    }



    @Bean
    public RabbitTemplate rabbitTemplate(RabbitTemplateConfigurer configurer, ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate();
        configurer.configure(template, connectionFactory);
        //使用json作为序列化协议
        template.setMessageConverter(new Jackson2JsonMessageConverter());
        return template;
    }
}
